package com.xbongbong.parent.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author sunshaoxiang
 * @ClassName DataUtil
 * @Description data工具类
 * @Date 2022/6/21 10:17
 * @Version 1.0
 **/
public class DataUtil {

    /**
     * 处理子表单数据
     * @param data 主表数据
     * @param subFormAttrList 子表单字段attr
     */
    public static void handleData4Subform(JSONObject data, List<String> subFormAttrList) {
        for (String attr : subFormAttrList){
            if (data.containsKey(attr)){
                JSONArray jsonArray = data.getJSONArray(attr);
                if (Objects.nonNull(jsonArray) && jsonArray.size() > 3){
                    data.put(attr, Arrays.asList(jsonArray.get(0),jsonArray.get(1)));
                }
            }
        }
    }

    /**
     * 取照片url集合
     * 重构前 -> com.xbongbong.saas.help.SaasUpdateHelp#getListFromFormData(com.alibaba.fastjson.JSONObject, java.lang.String)
     * @param data
     * @param attr
     * @return
     * @throws XbbException
     */
    public static List<Object> getListFromFormData(JSONObject data, String attr) throws XbbException {
        List<Object> photoList = new ArrayList<>();
        if (data == null || attr == null) {
            return photoList;
        }
        try {
            if (data.get(attr) == null) {
                return photoList;
            }
            JSONArray photoArray = data.getJSONArray(attr);
            for (Object obj : photoArray) {
                String tel = obj.toString();
                photoList.add(tel);
            }
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
        return photoList;
    }


}
